package com.demon.auto.config;

import com.demon.auto.handle.SignWebSocketHandler;
import com.demon.auto.interceptor.WebSocketAuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

/**
 * websocket配置
 *
 * @version 1.0
 * @author huangrz
 * @date 2025/02/13 14:18
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private SignWebSocketHandler signWebSocketHandler;

    @Autowired
    private WebSocketAuthInterceptor webSocketAuthInterceptor;

    @Value("${websocket.connect-timeout:1200}")
    private Integer connectTimeout; // 连接空闲超时(秒) 默认1200s (20分钟)

    @Value("${websocket.send-timeout:30}")
    private Integer sendTimeout; // 异步消息发送超时(秒) 默认30s

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(signWebSocketHandler, "/ws/sign")
                .setAllowedOrigins("*")
                .addInterceptors(webSocketAuthInterceptor);
    }

    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxSessionIdleTimeout(connectTimeout * 1000L); // 空闲超时
        container.setAsyncSendTimeout(sendTimeout * 1000L); // 异步发送超时
        return container;
    }

}